import questionsData from '@/data/questions.json'

// 题库数据
export const questionBank = {
  // 定义题目分类
  categories: [
    { id: 1, name: 'html' },
    { id: 2, name: 'css' },
    { id: 3, name: 'javascript' },
    { id: 4, name: 'vue' },
    { id: 5, name: 'react' },
    { id: 6, name: '计算机网络' },
    { id: 7, name: '浏览器原理' },
    { id: 8, name: '前端性能优化' },
    { id: 9, name: 'typescript' },
    { id: 10, name: '小程序' },
    { id: 11, name: '前端项目' },
  ],

  // 默认题目，作为初始数据
  defaultQuestions: [
    {
      id: 1,
      categoryId: 1,
      content: ['春天来了，', '开满了鲜花。'],
      blanks: ['小山坡上'],
      explanation: '这句话描述了春天小山坡上开满鲜花的景象。'
    },
    // ... 其他默认题目
  ],

  // 实际使用的题目数组
  questions: [],

  // 初始化题库
  initQuestions() {
    try {
      // 首先尝试从本地存储获取所有分类的题目
      let allQuestions = []
      this.categories.forEach(category => {
        const categoryQuestions = uni.getStorageSync(`questions_${category.id}`) || []
        allQuestions = allQuestions.concat(categoryQuestions)
      })

      if (allQuestions.length > 0) {
        this.questions = allQuestions
      } else {
        // 如果本地存储没有题目，则从 questions.json 文件加载
        if (questionsData && questionsData.questions) {
          this.questions = [...questionsData.questions]
          // 分片存储题目
          this.saveQuestionsByCategory(this.questions)
          console.log('从 questions.json 加载数据:', this.questions)
        } else {
          console.error('questions.json 数据格式错误')
          this.questions = []
        }
      }
    } catch (e) {
      console.error('初始化题库失败:', e)
      this.questions = []
    }
  },

  // 添加新题目
  addQuestion(question) {
    try {
      // 添加到内存中的数组
      this.questions.push(question)

      // 更新分类存储
      this.saveQuestionsByCategory(this.questions)

      // 同时更新总的题目存储
      uni.setStorageSync('questions', this.questions)

      return true
    } catch (e) {
      console.error('保存题目失败:', e)
      return false
    }
  },

  // 删除题目
  deleteQuestion(questionId) {
    const index = this.questions.findIndex(q => q.id === questionId)
    if (index !== -1) {
      this.questions.splice(index, 1)
      this.saveQuestionsByCategory(this.questions)

      // 同时更新总的题目存储
      uni.setStorageSync('questions', this.questions)
    }
  },

  // 更新题目（新增方法）
  updateQuestion(question) {
    try {
      const index = this.questions.findIndex(q => q.id === question.id)
      if (index !== -1) {
        this.questions[index] = question
        this.saveQuestionsByCategory(this.questions)
        uni.setStorageSync('questions', this.questions)
        return true
      }
      return false
    } catch (e) {
      console.error('更新题目失败:', e)
      return false
    }
  },

  // 按分类保存题目
  saveQuestionsByCategory(questions) {
    // 按分类分组
    const questionsByCategory = {}
    questions.forEach(q => {
      if (!questionsByCategory[q.categoryId]) {
        questionsByCategory[q.categoryId] = []
      }
      questionsByCategory[q.categoryId].push(q)
    })

    // 分别存储每个分类的题目
    Object.entries(questionsByCategory).forEach(([categoryId, categoryQuestions]) => {
      uni.setStorageSync(`questions_${categoryId}`, categoryQuestions)
    })
  },

  // 获取指定分类的题目
  getQuestionsByCategory(categoryId) {
    // 直接从分类存储中获取
    return uni.getStorageSync(`questions_${categoryId}`) || []
  },

  // 清空所有题目（恢复到默认题目）
  resetQuestions() {
    try {
      this.questions = [...this.defaultQuestions]
      uni.setStorageSync('questions', this.questions)
      return true
    } catch (e) {
      console.error('重置题库失败:', e)
      return false
    }
  },

  // 获取所有分类
  getCategories() {
    return this.categories
  },

  // 获取指定题目
  getQuestion(id) {
    return this.questions.find(q => q.id === id)
  },

  // 获取随机题目（可选指定分类）
  getRandomQuestion(categoryId = null) {
    const questions = categoryId
      ? this.getQuestionsByCategory(categoryId)
      : this.questions
    const randomIndex = Math.floor(Math.random() * questions.length)
    return questions[randomIndex]
  },

  // 导出题目到文件
  exportQuestionsToFile() {
    try {
      // 将题目数据写入本地存储
      uni.setStorageSync('questions', this.questions)

      // 导出题目数据为文本，方便复制到 questions.json 文件中
      const data = {
        questions: this.questions
      }
      console.log('请将以下数据复制到 data/questions.json 文件中：')
      console.log(JSON.stringify(data, null, 2))

      return true
    } catch (e) {
      console.error('导出题目失败:', e)
      return false
    }
  },

  // 从文件导入题目
  importQuestionsFromFile() {
    try {
      this.questions = [...questionsData.questions]
      // 同时更新本地存储
      uni.setStorageSync('questions', this.questions)
    } catch (e) {
      console.error('从文件导入题目失败:', e)
    }
  },

  // 导出题目数据为文本
  exportQuestionsToText() {
    try {
      const data = {
        questions: this.questions,
        categories: this.categories,
        questionStats: uni.getStorageSync('questionStats') || {}
      }
      // 转换为格式化的 JSON 字符串
      const jsonStr = JSON.stringify(data, null, 2)

      // 复制到剪贴板
      uni.setClipboardData({
        data: jsonStr,
        success: () => {
          uni.showToast({
            title: '数据已复制到剪贴板',
            icon: 'success'
          })
        }
      })
      return true
    } catch (e) {
      console.error('导出数据失败:', e)
      return false
    }
  },

  // 从文本导入题目
  importQuestionsFromText(jsonStr) {
    try {
      const data = JSON.parse(jsonStr)
      if (data) {
        if (Array.isArray(data.questions)) {
          this.questions = data.questions
          uni.setStorageSync('questions', this.questions)
        }
        if (Array.isArray(data.categories)) {
          this.categories = data.categories
          uni.setStorageSync('categories', this.categories)
        }
        if (data.questionStats) {
          uni.setStorageSync('questionStats', data.questionStats)
        }
        return true
      }
      return false
    } catch (e) {
      console.error('导入数据失败:', e)
      return false
    }
  },

  // 添加分类
  addCategory(category) {
    this.categories.push(category)
    // 保存到本地存储
    uni.setStorageSync('categories', this.categories)
  },

  // 删除分类
  deleteCategory(categoryId) {
    this.categories = this.categories.filter(c => c.id !== categoryId)
    // 同时删除该分类下的所有题目
    this.questions = this.questions.filter(q => q.categoryId !== categoryId)
    // 保存到本地存储
    uni.setStorageSync('categories', this.categories)
    uni.setStorageSync('questions', this.questions)
  },

  // 添加更新分类名称的方法
  updateCategoryName(categoryId, newName) {
    const category = this.categories.find(c => c.id === categoryId)
    if (category) {
      category.name = newName
      // 保存到本地存储
      uni.setStorageSync('categories', this.categories)
    }
  },

  // 添加这个方法来重置本地存储
  resetLocalStorage() {
    try {
      // 本地存储
      uni.removeStorageSync('questions')
      // 重新初始化
      this.initQuestions()
    } catch (e) {
      console.error('重置本地存储失败:', e)
    }
  }
}

// 确保在导出时初始化题库
questionBank.initQuestions()

// 答题记录存储
export const questionStorage = {
  // 保存答题记录
  saveProgress(questionId, isCorrect) {
    try {
      const key = `question_stats_${questionId}`
      const stats = uni.getStorageSync(key) || {
        totalAttempts: 0,
        correctCount: 0,
        wrongCount: 0,
        lastAttemptTime: null
      }

      stats.totalAttempts++
      if (isCorrect) {
        stats.correctCount++
      } else {
        stats.wrongCount++
      }
      stats.lastAttemptTime = Date.now()

      uni.setStorageSync(key, stats)

      // 保存答题记录
      const attemptsKey = `question_attempts_${questionId}`
      const attempts = uni.getStorageSync(attemptsKey) || []
      attempts.push({
        isCorrect,
        timestamp: Date.now()
      })
      // 只保留最近10次记录
      if (attempts.length > 10) {
        attempts.shift()
      }
      uni.setStorageSync(attemptsKey, attempts)
    } catch (e) {
      console.error('保存进度失败:', e)
    }
  },

  // 获取题目统计信息
  getQuestionStats(questionId) {
    try {
      const key = `question_stats_${questionId}`
      return uni.getStorageSync(key) || {
        totalAttempts: 0,
        correctCount: 0,
        wrongCount: 0,
        lastAttemptTime: null
      }
    } catch (e) {
      console.error('获取题目统计失败:', e)
      return {
        totalAttempts: 0,
        correctCount: 0,
        wrongCount: 0,
        lastAttemptTime: null
      }
    }
  },

  // 重置题目统计信息
  resetQuestionStats(questionId) {
    const key = `question_stats_${questionId}`
    uni.setStorageSync(key, {
      totalAttempts: 0,
      correctCount: 0,
      wrongCount: 0,
      lastAttemptTime: null
    })
  },

  // 清除所有进度
  clearAllProgress() {
    try {
      // 获取所有题目
      const questions = questionBank.questions

      // 清除所有题目的统计信息
      questions.forEach(question => {
        const key = `question_stats_${question.id}`
        uni.removeStorageSync(key)
      })

      // 清除首次学习日期
      uni.removeStorageSync('firstStudyDay')
    } catch (e) {
      console.error('清除进度失败:', e)
    }
  },

  // 判断是否为错题（正确率低于80%且已练习过）
  isWrongQuestion(questionId) {
    const stats = this.getQuestionStats(questionId)
    return stats.totalAttempts > 0 && this.getQuestionAccuracy(questionId) < 80
  },

  // 获取题目正确率
  getQuestionAccuracy(questionId) {
    const stats = this.getQuestionStats(questionId)
    if (stats.totalAttempts === 0) return 0
    return Math.round((stats.correctCount / stats.totalAttempts) * 100)
  },

  // 获取最近的答题记录
  getRecentAttempts(questionId, count) {
    const key = `question_attempts_${questionId}`
    const attempts = uni.getStorageSync(key) || []
    return attempts.slice(-count)
  },

  // 判断是否应该加入错题集
  shouldAddToWrongSet(questionId) {
    const stats = this.getQuestionStats(questionId)

    // 条件1: 至少练习过2次
    if (stats.totalAttempts < 2) return false

    // 条件2: 正确率低于75%
    const accuracy = this.getQuestionAccuracy(questionId)
    if (accuracy < 75) return true

    // 条件3: 最近3次答题中有2次以上错误
    const recentAttempts = this.getRecentAttempts(questionId, 3)
    const recentWrongs = recentAttempts.filter(attempt => !attempt.isCorrect).length
    if (recentWrongs >= 2) return true

    return false
  },

  // 判断是否应该从错题集移除
  shouldRemoveFromWrongSet(questionId) {
    const stats = this.getQuestionStats(questionId)

    // 条件1: 至少练习过3次
    if (stats.totalAttempts < 3) return false

    // 条件2: 正确率达到80%
    const accuracy = this.getQuestionAccuracy(questionId)
    if (accuracy < 80) return false

    // 条件3: 最近3次答题全部正确
    const recentAttempts = this.getRecentAttempts(questionId, 3)
    const allCorrect = recentAttempts.every(attempt => attempt.isCorrect)

    return allCorrect
  }
}

// 将题目按分类分片存储
const saveQuestions = (questions) => {
  // 按分类分组
  const questionsByCategory = {}
  questions.forEach(q => {
    if (!questionsByCategory[q.categoryId]) {
      questionsByCategory[q.categoryId] = []
    }
    questionsByCategory[q.categoryId].push(q)
  })

  // 分别存储每个分类的题目
  Object.entries(questionsByCategory).forEach(([categoryId, questions]) => {
    uni.setStorageSync(`questions_${categoryId}`, questions)
  })
}

// 读取时按需加载
const loadQuestionsByCategory = (categoryId) => {
  return uni.getStorageSync(`questions_${categoryId}`) || []
} 